<template>
  <view>
    <!-- <page-meta>
			<navigation-bar :title="customer.name" front-color="#000000" background-color="#F1F1F1" />
		</page-meta> -->
    <view class="chat" :style="{paddingBottom:emoji.visible ?'420rpx':'120rpx'}">

      <view class="chat-box">
        <view class="scroll-view">
          <image v-if="history.loading" class="history-loaded" src="/static/images/loading.svg" />
          <view v-else>
            <view v-if="group_id==1" style="position: fixed;left:0;top:0;">
              <text>剩余时间:</text>
              <u-count-down :timestamp="timestamp" @end="handleEnd"></u-count-down>
            </view>
            <view class="history-loaded" v-if="history.allLoaded">已经没有更多的历史消息</view>
            <view class="load" v-else>下拉获取历史消息</view>
          </view>
          <!--已经收到的消息-->
          <view v-for="(item,index) in history.messages" :key="index">
            <!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
            <view class="time-lag">{{item.showTime}}</view>
            <!--消息内容-->
            <view class="message-item">
              <view v-if="item.type === 'CS_ACCEPT'" class="accept-message">
                <text>{{ item.senderData.name }}已接入</text>
              </view>
              <view v-else-if="item.type === 'CS_END'" class="accept-message">
                <text>{{ item.senderData.name }}已结束会话</text>
              </view>
              <view v-else-if="item.type === 'CS_TRANSFER'" class="accept-message">
                <text>{{
								item.senderId === item.id ? '已转接给' + item.payload.transferTo.data.name :
								'已接入来自' + item.senderData.name + '的转接'
								}}</text>
              </view>
              <view v-else
                :class="item.senderId !== customer.id ? 'message-item-content self' : 'message-item-content'">
                <view class="avatar" v-if="item.senderId === currentAgent.id">
                  <image :src="currentAgent.avatar" />
                </view>
                <view class="avatar" v-else>
                  <image :src="item.senderData.avatar" />
                </view>
                <view class="content">
                  <view class="message-payload">
                    <image src="/static/images/pending.gif" class="pending" v-if="item.status === 'sending'"></image>
                    <image src="/static/images/failed.png" class="send-fail" v-if="item.status == 'fail'"></image>
                    <rich-text class="text-content" :nodes="item.node" v-if="item.type ==='text'">
                    </rich-text>
                    <image class="image-content" v-if="item.type === 'image'" :src="item.payload.url"
                      @click="previewImage(item)" mode="widthFix" :style="{height:item.imageHeight}" />
                    <view v-if="item.type ==='audio'" class="audio-content" @click="playAudio(item)">
                      <view class="audio-facade" :style="{width:item.width}">
                        <image v-if="audioPlayer.playingMessage.messageId === item.messageId"
                          class="audio-facade-bg audio-play-icon" src="/static/images/play.gif"></image>
                        <image v-else class="audio-facade-bg" src="/static/images/voice.png">
                        </image>
                        <view class="record-second">{{item.finalDuration}}<text>"</text></view>
                      </view>
                    </view>
                    <view class="video-snapshot" @click="playVideo" v-if="item.type == 'video'">
                      <image class="thumbnail-image" :src="item.payload.thumbnail.url" mode="aspectFit"></image>
                      <image class="play-icon" src="/static/images/videoImage/play.png" mode="aspectFit"></image>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <!--发送消息，视频，语音，自定义消息操作-->
        <view class="chat-footer">
          <view v-if="customerStatus.status==='PENDING'" class="accept-session">
            <view class="accept-info">会话已等待{{pendingTime.duration}}</view>
            <view class="accept-btn" @click="acceptSession" v-if="group_id==2 || (group_id==1 && timestamp)">接入</view>
          </view>

          <view v-else-if="customerStatus.status==='ACCEPTED' && currentAgent.id !== customerStatus.agent.id"
            class="accept-session">
            <view class="accepted-info">{{ customerStatus.agent.data.name }}已接入</view>
          </view>
          <view v-else-if="customerStatus.status==='FREE'" class="accept-session">
            <view class="accept-info">暂未接入此用户</view>
            <view class="accept-btn" @click="acceptSession" v-if="group_id==2 || (group_id==1 && timestamp)">主动接入</view>
          </view>
          <view v-else class="action-box">
            <view class="session-action">
              <view class="session-action-item" @click="showTransferForm" v-if="group_id==2">转接</view>
              <view class="session-action-item" @click="endSession" v-if="group_id==2 || (group_id==1 && timestamp)">
                结束会话</view>
              <view class="session-action-item" @click="sendOrder" v-if="group_id==2">发送订单</view>
            </view>
            <view class="action-top">
              <view @click="switchAudioKeyboard">
                <image class="more" v-if="audio.visible" src="/static/images/jianpan.png"></image>
                <image class="more" v-else src="/static/images/audio.png"></image>
              </view>
              <view v-if="audio.visible" class="record-input" @touchend.stop="onRecordEnd" @touchstart.stop="onRecordStart">
                {{ recorderManager.recording ? '松开发送' : '按住录音' }}
              </view>
              <!-- <GoEasyRecorder id="videoPlayer"></GoEasyRecorder> -->
              <!-- GoEasyIM最大支持3k的文本消息，如需发送长文本，需调整输入框maxlength值 -->
              <u-input v-else type="text" maxlength="700" placeholder="发送消息" class="msg-input-box" @input="setContent"
                @focus="messageInputFocusin" v-model="text" />
              <view class="action-icon" @click="switchEmojiKeyboard">
                <image class="more-icon" v-if="emoji.visible" src="/static/images/jianpan.png">
                </image>
                <image class="more-icon" v-else src="/static/images/emoji.png"></image>
              </view>
              <view class="action-icon">
                <image src="/static/images/more.png" class="more-icon" @click="showOtherTypesMessagePanel"></image>
              </view>
              <view v-if="text" class="send-btn-box">
                <text class="btn" @click="sendTextMessage">发送</text>
              </view>
            </view>
            <!--展示表情列表-->
            <view class="action-bottom" v-if="emoji.visible" style="justify-content: space-around">
              <image class="image" v-for="(item,emojiKey,index) in emoji.map" :key="index" :src="emoji.url + item"
                @click="selectEmoji(emojiKey)"></image>
            </view>
            <!--展示其他消息类型面板-->
            <view class="action-bottom" v-if="otherTypesMessagePanelVisible">
              <view class="more-item" @click="sendImageMessage">
                <image class="operation-icon" src="/static/images/picture.png" />
                <text class="operation-title">图片</text>
              </view>
              <!-- <view class="more-item" @click="sendVideoMessage">
								<image class="operation-icon" src="/static/images/video.png"></image>
								<text class="operation-title">视频</text>
							</view> -->
              <!-- <view class="more-item" @click="showOrderMessageList">
								<image class="operation-icon" src="/static/images/order.png"></image>
								<text class="operation-title">订单</text>
							</view> -->
            </view>
          </view>
          <view v-if="audio.recording" class="record-loading"></view>
        </view>
        <view v-if="transferForm.visible" class="transfer-mask" @click="hideTransferForm"></view>
        <view v-if="transferForm.visible" class="transfer-list">
          <view class="title">
            <view class="close" @click="hideTransferForm">×</view>
            <view>选择转接的对象</view>
          </view>
          <view v-for="(item,index) in transferForm.agents" :key="index" @click="transfer(item)">
            <view class="transfer-body">
              <image :src="item.data.avatar" class="agent-img"></image>
              <view class="agent-name">{{ item.data.name }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <u-popup v-model="orderDialog" mode="center">
      <view class="box">
        <view class="box-title">
          创建订单
        </view>
        <view class="dialog-item">
          <view class="label">
            金额
          </view>
          <input class="dialog-ipt" v-model="orderParams.total_amount" placeholder="请输入" placeholder-style="styles"
            type="text">
        </view>
        <view class="dialog-item">
          <view class="label">
            时长(分钟)
          </view>
          <input class="dialog-ipt" v-model="orderParams.fi_time" placeholder="请输入" placeholder-style="styles"
            type="text">
        </view>
        <view class="dialog-item">
          <view class="label">
            律师
          </view>
          <input class="dialog-ipt" disabled @click="openLvshi" v-model="lvshiname" placeholder="请选择律师"
            placeholder-style="styles" type="text">
        </view>
        <view class="dialog-item">
          <view class="label">
            咨询类型
          </view>
          <input class="dialog-ipt" disabled @click="openZixun" v-model="zixunname" placeholder="请选择咨询类型"
            placeholder-style="styles" type="text">
        </view>
        <view class="footer">
          <view class="footer-fl" @click="handleClose">取消</view>
          <view class="footer-fr" @click="handleSave">确定</view>
        </view>
      </view>
    </u-popup>
    <u-picker mode="selector" v-model="roleShow" :range="selector" @confirm="handlePickerConfirm" />
    <u-picker mode="selector" v-model="lvshiShow" :range="selectorlvshi" :default-selector="[0]" range-key="name"
      @confirm="handlePickerlvshi" />
    <!-- 类型 -->
    <u-picker mode="selector" :range="actionTypeList" v-model="isShowType" :default-selector="[0]" range-key="name"
      @confirm="handleType"></u-picker>
  </view>
</template>

<script>
  import EmojiDecoder from '@/utils/service-lib/EmojiDecoder';
  import {
    formatDate,
    formateTime
  } from '@/utils/service-lib/utils';
  let emojiUrl = 'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/';
  let emojiMap = {
    '[么么哒]': 'emoji_3@2x.png',
    '[乒乓]': 'emoji_4@2x.png',
    '[便便]': 'emoji_5@2x.png',
    '[信封]': 'emoji_6@2x.png',
    '[偷笑]': 'emoji_7@2x.png',
    '[傲慢]': 'emoji_8@2x.png'
  };
  const IMAGE_MAX_WIDTH = 200;
  const IMAGE_MAX_HEIGHT = 150;
  const recorderManager = uni.getRecorderManager();
  export default {
    data() {
      return {
        group_id: null,
        roleShow: false,
        show: false,
        order_no: '',
        currentAgent: null,
        csteam: null,
        customer: null,
        customerStatus: {
          status: ""
        },
        to: {}, //用于创建消息时传入
        history: {
          messages: [],
          allLoaded: false,
          loading: true
        },
        text: '',
        //定义表情列表
        emoji: {
          url: emojiUrl,
          map: emojiMap,
          visible: false,
          decoder: new EmojiDecoder(emojiUrl, emojiMap),
        },

        // 语音播放器
        audioPlayer: {
          innerAudioContext: null,
          playingMessage: null,
        },
        audio: {
          startTime: null,
          //语音录音中
          recording: false,
          //录音按钮展示
          visible: false
        },
        //是否展示‘其他消息类型面板’
        otherTypesMessagePanelVisible: false,
        orderList: {
          orders: [],
          visible: false,
        },
        transferForm: {
          visible: false,
          agents: [],
          to: {}
        },
        pendingTime: {
          timer: null,
          duration: ''
        },
        selector: ['客服', '律师'],
        roleText: '',
        orderDialog: false,
        orderParams: {
          luid: "",
          uuid: "",
          total_amount: "",
          type_id: "",
          fi_time: ""
        },
        lvshiname: "",
        lvshiList: [],
        selectorlvshi: [],
        lvshiShow: false,
        actionTypeList: [],
        isShowType: false,
        zixunname: "",
        timestamp: null,
      };
    },
    onPullDownRefresh() {
      this.loadHistoryMessage(false);
    },
    beforeDestroy() {
      // this.goEasy.im.off(this.GoEasy.IM_EVENT.CS_MESSAGE_RECEIVED, this.onMessageReceived);
    },
    onLoad(options) {
      let teamId = uni.getStorageSync('team').id;
      this.csteam = this.goEasy.im.csteam(teamId);
      this.group_id = uni.getStorageSync('group_id');
      this.customer = JSON.parse(options.to);
      console.log("在跟哪个用户聊天", this.customer);
      this.orderParams.uuid = this.customer.id;
      let userinfo = uni.getStorageSync('userinfo');
      // 获取初始数据并加载
      this.currentAgent = {
        avatar: userinfo.avatar,
        id: userinfo.id,
        name: userinfo.nickname
      };
      console.log("聊天室客服", this.currentAgent);
      this.to = {
        type: this.GoEasy.IM_SCENE.CS,
        id: this.customer.id, //客户的id
        data: {
          name: this.customer.name,
          avatar: this.customer.avatar,
          id: this.customer.id
        },
      }
      uni.setNavigationBarTitle({
        title: this.customer.name
      });
      this.initTypeData();
      this.loadHistoryMessage(true);
      this.listenCustomer();
      // 语音播放器
      this.initialAudioPlayer();
      // 录音监听器
      this.initRecorderListeners();
      // this.goEasy.im.on(this.GoEasy.IM_EVENT.CS_MESSAGE_RECEIVED, this.onMessageReceived);
    },
    onUnload() {
      this.csteam.cancelListenCustomer({
        onSuccess: () => {
          console.log('cancelListenCustomer successfully ');
        },
        onFailed: (error) => {
          console.log('failed to cancelListenCustomer:', error);
        },
      });
      if (this.pendingTime.timer) {
        clearInterval(this.pendingTime.timer);
      }
    },
    methods: {
      openZixun() {
        this.isShowType = true;
      },
      handleType(e) {
        this.zixunname = this.actionTypeList[e].name;
        this.orderParams.type_id = this.actionTypeList[e].id;
      },
      // 咨询类型
      initTypeData() {
        this.$u.api._getmdss().then(res => {
          this.actionTypeList = res.data;
        })
      },
      handlePickerlvshi(e) {
        console.log("选择的律师index", e);
        this.lvshiname = this.selectorlvshi[e].name;
        this.orderParams.luid = this.selectorlvshi[e].id;
        this.lvshiShow = false;
      },
      handleClose() {
        this.orderDialog = false;
      },
      openLvshi() {
        if (this.selectorlvshi && this.selectorlvshi.length > 0) {
          this.lvshiShow = true;
        } else {
          uni.showToast({
            title: '暂无可选的律师',
            duration: 3000,
            icon: 'none'
          });
        }
      },
      handleSave() {
        console.log("orderParams", this.orderParams);
        this.$u.api._setOrder(this.orderParams).then(res => {
          console.log("订单已发送", res);
          this.orderParams.luid = "";
          this.orderParams.total_amount = "";
          this.orderParams.type_id = "";
          this.orderParams.fi_time = "";
          this.orderDialog = false;
          this.text = "通过以下链接进行咨询付费:" + "<br>" + res.data.pay_url;
          this.sendTextMessage();
        })
      },
      // 发送订单
      sendOrder() {
        // 发送订单之前清空数据
        this.lvshiList = [];
        this.selectorlvshi = [];
        this.orderDialog = true;
        this.csteam.agents({
          onSuccess: (result) => {
            console.log("在线工作人员", result.content);
            this.lvshiList = result.content.filter(v => v.data.id.includes("lvshi"))
            console.log("要选中的律师", this.lvshiList);
            if (this.lvshiList && this.lvshiList.length > 0) {
              this.lvshiList.forEach(v => {
                this.selectorlvshi.push({
                  name: v.data.name,
                  id: v.data.id
                })
              })
            }
            console.log("过滤律师", this.selectorlvshi);
          },
          onFailed: (error) => {
            console.log('query online agents failed', error);
          }
        });
      },
      switchAudioKeyboard() {
        console.log("点击了录音");
        this.audio.visible = !this.audio.visible;
        if (this.audio.visible) {
          uni.authorize({
            scope: 'scope.record',
            success() {
              console.log("录音权限开启成功");
            },
            fail: (e) => {
              console.log("录音权限开启失败");
            }
          });
        }
      },
      onRecordStart() {
        try {
          recorderManager.start();
        } catch (e) {
          uni.showModal({
            title: '录音错误',
            content: '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
          });
        }
      },
      onRecordEnd() {
        try {
          recorderManager.stop();
        } catch (e) {
          console.log(e);
        }
      },
      initRecorderListeners() {
        console.log("initRecorderListeners")
        // 监听录音开始
        recorderManager.onStart(() => {
          console.log("录音开始")
          this.audio.recording = true;
          this.audio.startTime = Date.now();
        });
        //录音结束后，发送
        recorderManager.onStop((res) => {
          console.log("录音结束")
          let endTime = Date.now();
          this.audio.recording = false;
          let duration = endTime - this.audio.startTime;
          if (duration < 1000) {
            uni.showToast({
              icon: 'error',
              title: '录音时间太短',
              duration: 500
            });
            return;
          }
          res.duration = duration;
          this.sendAudioMessage(res);
        });
        // 监听录音报错
        recorderManager.onError((res) => {
          this.audio.recording = false;
          console.log("录音失败", res);
          // uni.showToast({
          // 	icon: 'none',
          // 	title: '录音失败,请检查麦克风权限',
          // 	duration: 1000
          // });
        })
      },
      sendAudioMessage(file) {
        this.csteam.createAudioMessage({
          to: this.to,
          file: file,
          onProgress: function(progress) {
            console.log(progress)
          },
          onSuccess: (message) => {
            this.sendMessage(message);
          },
          onFailed: (e) => {
            // console.log('error :', e);
          }
        });
      },
      listenCustomer() {
        let teamId = uni.getStorageSync('team').id;
        let csteam = this.goEasy.im.csteam(teamId);
        console.log("聊天室客服Goeasy", csteam);
        csteam.listenCustomer({
          id: this.customer.id,
          onSuccess: () => {
            console.log('listen customer successfully');
            this.markMessageAsRead();
          },
          onFailed: (error) => {
            console.log('failed to listen customer:', error);
          },
          onStatusUpdated: (customerStatus) => {
            console.log("克服克服", customerStatus)
            if (customerStatus.status === 'PENDING') {
              this.updatePendingTime(customerStatus.start);
            }
            this.customerStatus = customerStatus;
            // 如果律师是已接入状态,直接调倒计时
            console.log("当前接入的客服", this.customerStatus.status);
            console.log("当前登入的用户信息", this.currentAgent);
            console.log("group_id", this.group_id)
            if (this.customerStatus.status === 'ACCEPTED' && this.group_id == 1) {
              this.getTimes();
            }
            this.customerStatus = customerStatus;
          },
          onNewMessage: (message) => {
            this.onReceivedMessage(message);
          },
        })
        // csteam.listenCustomer({
        // 	id: this.customer.id,
        // 	onSuccess(){
        //         console.log("1")
        // 		this.markMessageAsRead();
        // 	},
        // 	onFailed(error){
        //         console.log("2")
        //       },
        // 	onStatusUpdated(customerStatus){
        //         console.log("谁跟用户建立了联系", customerStatus);
        // 		if (customerStatus.status === 'PENDING') {
        // 			this.updatePendingTime(customerStatus.start);
        // 		}
        // 		this.customerStatus = customerStatus;
        // 		// 如果律师是已接入状态,直接调倒计时
        // 		if (this.customerStatus.status === 'ACCEPTED' && this.group_id == 1) {
        // 			this.getTimes();
        // 		}
        // 	},
        // 	onNewMessage(message){
        //         console.log("4")
        // 		this.onReceivedMessage(message);
        // 	},
        // })
      },
      initialAudioPlayer() {
        console.log("initialAudioPlayer")
        this.audioPlayer.innerAudioContext = uni.createInnerAudioContext()
        this.audioPlayer.innerAudioContext.onEnded(() => {
          this.audioPlayer.playingMessage = null;
        });
        this.audioPlayer.innerAudioContext.onStop(() => {
          this.audioPlayer.playingMessage = null;
        });
      },
      updatePendingTime(time) {
        this.pendingTime.duration = formateTime(time);
        clearInterval(this.pendingTime.timer);
        let timer = setInterval(() => {
          let duration = formateTime(time)
          this.pendingTime.duration = duration
        }, 1000);
        this.pendingTime.timer = timer;
      },
      onReceivedMessage(newMessage) {
        //如果该消息已存在，跳过
        if (this.history.messages.findIndex((message) => newMessage.id === message.messageId) >= 0) {
          return;
        }
        this.history.messages.push(newMessage);
        this.renderMessages(this.history.messages);
        this.markMessageAsRead();
        this.scrollToBottom();
      },
      markMessageAsRead() {
        this.csteam.markMessageAsRead({
          type: this.GoEasy.IM_SCENE.CS,
          id: this.customer.id,
          onSuccess: function() {
            // console.log('标记已读成功');
          },
          onFailed: function(error) {
            // console.log('标记已读失败', error);
          }
        });
      },
      /**
       * 核心就是设置高度，产生明确占位
       *
       * 小  (宽度和高度都小于预设尺寸)
       *    设高=原始高度
       * 宽 (宽度>高度)
       *    高度= 根据宽度等比缩放
       * 窄  (宽度<高度)或方(宽度=高度)
       *    设高=MAX height
       *
       * @param width,height
       * @returns number
       */
      getImageHeight(width, height) {
        if (width < IMAGE_MAX_WIDTH && height < IMAGE_MAX_HEIGHT) {
          return height * 2;
        } else if (width > height) {
          return (IMAGE_MAX_WIDTH / width * height) * 2;
        } else if (width === height || width < height) {
          return IMAGE_MAX_HEIGHT * 2;
        }
      },
      loadHistoryMessage(scrollToBottom) {
        this.history.loading = true;
        let lastMessageTimeStamp;
        let lastMessage = this.history.messages[0];
        if (lastMessage) {
          lastMessageTimeStamp = lastMessage.timestamp;
        }
        let limit = 10;
        this.csteam.history({
          id: this.customer.id,
          type: this.GoEasy.IM_SCENE.CS,
          lastTimestamp: lastMessageTimeStamp,
          limit: limit,
          onSuccess: (result) => {
            uni.stopPullDownRefresh();
            this.history.loading = false;
            let messages = result.content;
            if (messages.length === 0) {
              this.history.allLoaded = true
            } else {
              let messageList
              if (lastMessageTimeStamp) {
                messageList = messages.concat(this.history.messages);
              } else {
                messageList = messages;
              }
              if (scrollToBottom) {
                this.scrollToBottom();
              }
              this.renderMessages(messageList);
            }
          },
          onFailed: (error) => {
            //获取失败
            // console.log('获取历史消息失败, code:' + error.code + ',错误信息:' + error.content);
            uni.stopPullDownRefresh();
            this.history.loading = false;
          }
        });
      },
      isOnline() {
        return new Promise((resolve, reject) => {
          this.csteam.isOnline({
            onSuccess: (result) => {
              resolve(result);
            },
            onFailed: (error) => {
              // console.log('获取在线状态失败，error:', error)
              reject(error);
            }
          })
        })
      },
      // 主动接入
      async acceptSession() {
        if (await this.isOnline()) {
          this.csteam.accept({
            customer: {
              id: this.customer.id,
              data: {
                name: this.customer.name,
                avatar: this.customer.avatar
              }
            },
            onSuccess: () => {
              // console.log('accept successfully.');
              clearInterval(this.pendingTime.timer);
              // 如果是律师调接口获取聊天时长
              if (this.group_id == 1) {
                this.getTimes();
              }
            },
            onFailed: (error) => {
              // console.log('accept failed', error);
            }
          });
        } else {
          uni.showToast({
            title: '您还不是一名该团队的在线客服，请上线再操作',
            duration: 3000,
            icon: 'none'
          });
        }
      },
      // 律师聊天时长到时间，自动断开会话
      handleEnd() {
        this.timestamp = null;
        this.endSession();
        // this.csteam.agents({
        //   onSuccess: (result) => {
        //     let kefu_list = result.content.filter(v => v.id.includes("kefu"))
        //     console.log("准备随机分配客服", kefu_list);
        //     if (kefu_list && kefu_list.length > 0) {
        //       this.transfer(kefu_list[0]);
        //       this.endSession();
        //     } else {
        //       uni.showToast({
        //         title: '暂时无客服在线,请稍后重试',
        //         duration: 3000,
        //         icon: 'none'
        //       });
        //     }
        //   },
        //   onFailed: (error) => {
        //     console.log('query online agents failed', error);
        //   }
        // });
      },
      endSession() {
        this.csteam.end({
          id: this.customer.id,
          onSuccess: () => {
            console.log('end successfully.');
          },
          onFailed: (error) => {
            console.log('end failed', error);
          }
        })
      },
      showTransferForm() {
        this.roleShow = !this.roleShow;
      },
      async handlePickerConfirm(e) {
        this.roleText = this.selector[e];
        console.log("转接给谁111", this.roleText);
        const {
          data
        } = await this.$u.api._trasTranfer({
          uuid: this.customer.id
        });
        console.log("查看该用户买了哪些律师的钟1", data);
        this.csteam.agents({
          onSuccess: async (result) => {
            let agents = [];
            console.log("全部集合111", result.content);
            if (this.roleText == "律师") {
              console.log("查看该用户买了哪些律师的钟2", data);
              // 如果data=[],说明该用户没有下单
              if (data && data.length > 0) {
                let list = result.content.filter(v => v.data.id.includes("lvshi"));
                console.log("律师集合", list);
                agents = list.filter(item => data.includes(item.data.id));
                console.log("过滤后可转接的律师", agents);
              } else {
                uni.showToast({
                  title: `暂无可转接的律师`,
                  duration: 1500,
                  icon: 'none'
                });
              }
            } else {
              let list = result.content.filter(v => v.data.id.includes("kefu"));
              console.log("客服集合", list);
              agents = list.filter(item => item.data.id !== this.currentAgent.id);
              console.log("过滤后可转接的客服", list);
            }
            if (agents.length === 0) {
              uni.showToast({
                title: `暂无可转接的${this.roleText}`,
                duration: 1500,
                icon: 'none'
              });
            } else {
              this.transferForm.visible = true;
              this.transferForm.agents = agents;
              this.otherTypesMessagePanelVisible = false
            }
          },
          onFailed: (error) => {
            console.log('query online agents failed', error);
          }
        });
      },
      handleConfirm() {
        let parm = {
          order_no: this.order_no,
          luid: this.transferForm.to.id
        }
        this.$u.api._kfsendloans(parm).then(res => {
          this.csteam.transfer({
            customerId: this.customer.id,
            agentId: this.transferForm.to.id,
            onSuccess: () => {
              this.hideTransferForm();
              console.log('transfer successfully.');
            },
            onFailed: (error) => {
              console.log('transfer failed', error);
            }
          })
        })
      },
      transfer(item) {
        console.log("转接的客服对象", item);
        this.transferForm.to = item;
        this.csteam.transfer({
          customerId: this.customer.id,
          agentId: this.transferForm.to.id,
          onSuccess: () => {
            this.hideTransferForm();
            console.log('转接 successfully.');
          },
          onFailed: (error) => {
            console.log('transfer failed', error);
          }
        })
        // if (this.roleText == '律师') {
        // 	this.show = !this.show;
        // } else {
        // 	this.csteam.transfer({
        // 		customerId: this.customer.id,
        // 		agentId: this.transferForm.to.id,
        // 		onSuccess: () => {
        // 			this.hideTransferForm();
        // 			console.log('transfer successfully.');
        // 		},
        // 		onFailed: (error) => {
        // 			console.log('transfer failed', error);
        // 		}
        // 	})
        // }
      },
      hideTransferForm() {
        this.transferForm.visible = false;
      },
      sendTextMessage() {
        // 发送文本与表情
        if (this.text.trim() !== '') {
          this.csteam.createTextMessage({
            text: this.text,
            to: this.to,
            onSuccess: (message) => {
              this.sendMessage(message);
            },
            onFailed: (err) => {
              console.log("创建消息err:", err);
            }
          });
        }
        this.text = '';
      },
      sendImageMessage() {
        // 发送图片
        uni.chooseImage({
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            res.tempFiles.forEach((file) => {
              this.csteam.createImageMessage({
                file: file,
                to: this.to,
                onProgress: (progress) => {
                  console.log(progress)
                },
                onSuccess: (message) => {
                  this.otherTypesMessagePanelVisible = false;
                  this.sendMessage(message);
                },
                onFailed: (e) => {
                  console.log('error :', e);
                }
              });
            })
          }
        });
      },
      sendVideoMessage() {
        // 发送视频
        uni.chooseMedia({
          count: 9,
          mediaType: ['video'],
          sourceType: ['album', 'camera'],
          maxDuration: 30,
          camera: 'back',
          success: (res) => {
            res.tempFiles.forEach((file) => {
              this.csteam.createVideoMessage({
                file: file,
                to: this.to,
                onProgress: (progress) => {
                  console.log(progress)
                },
                onSuccess: (message) => {
                  this.otherTypesMessagePanelVisible = false;
                  this.sendMessage(message);
                },
                onFailed: (e) => {
                  console.log('error :', e);
                }
              });
            })
          }
        })
      },
      showOrderMessageList() {
        let orders = restApi.getOrderList();
        this.otherTypesMessagePanelVisible = false;
        this.orderList.orders = orders;
        this.orderList.visible = true;
      },
      hideOrderMessageList() {
        this.orderList.visible = false;
      },
      sendMessage(message) {
        let messages = this.history.messages;
        messages.push(message);
        this.renderMessages(messages);
        this.scrollToBottom();
        this.goEasy.im.sendMessage({
          message: message,
          onSuccess: (message) => {
            this.renderMessages(this.history.messages);
          },
          onFailed: (error) => {
            if (error.code === 507) {
              console.log(
                '发送语音/图片/视频/文件失败，没有配置OSS存储，详情参考：https://docs.goeasy.io/2.x/im/message/media/alioss'
              );
            } else {
              console.log('发送失败:', error);
            }
            this.renderMessages(this.history.messages);
          }
        });
      },
      scrollToBottom() { // 滑动到最底部
        setTimeout(() => {
          uni.pageScrollTo({
            scrollTop: 200000,
            duration: 10
          });
        }, 600)
      },
      renderMessages(messages) {
        messages.forEach((message, index) => {
          if (index === 0) {
            // 当页面只有一条消息时，显示发送时间
            message.showTime = formatDate(message.timestamp);
          } else {
            // 当前消息与上条消息的发送时间进行比对，超过5分钟则显示当前消息的发送时间
            if (message.timestamp - messages[index - 1].timestamp > 5 * 60 * 1000) {
              message.showTime = formatDate(message.timestamp);
            }
          }
          if (message.type === 'text') {
            // 渲染表情与文本消息
            let text = this.emoji.decoder.decode(message.payload.text);
            message.node = text;
          }
          if (message.type === 'image') {
            message.imageHeight = this.getImageHeight(message.payload.width, message.payload.height) +
              'rpx';
          }
          if (message.type === 'audio') {
            message.width = Math.ceil(message.payload.duration) * 7 + 80 + 'rpx';
            message.finalDuration = Math.ceil(message.payload.duration)
          }
        });
        // group_id 1:律师 2:客服. 律师聊天窗口只展示自己跟用户的聊天
        if (this.group_id == 1) {
          this.history.messages = messages.filter(v => v.senderId == this.currentAgent.id || v.senderId == this
            .customer.id);
        } else {
          this.history.messages = messages;
        }
        console.log("获取历史消息", this.history.messages);

      },
      // 获取聊天时长
      getTimes() {
        let params = {
          luid: this.currentAgent.id,
          uuid: this.customer.id
        }
        this.$u.api._layTranfer(params).then(res => {
          console.log("获取聊天时长", res);
          this.timestamp = res.data.countdown;
          if (this.timestamp == 0) {
            this.endSession();
          }
          if (this.timestamp == null) {
            this.endSession();
          }
        }).catch(err => {
          console.log("无效订单-直接结束会话");
          this.endSession();
        })
      },
      setContent(e) {
        // 监听输入的消息
        this.text = e;
      },
      playVideo(e) {
        //播放视频
        this.selectComponent('#videoPlayer').play({
          url: e.currentTarget.dataset.url,
          duration: e.currentTarget.dataset.duration
        });
      },
      playAudio(audioMessage) {
        let url = encodeURI(audioMessage.payload.url);
        console.log("播放文件", url);
        let playingMessage = this.audioPlayer.playingMessage;
        if (playingMessage) {
          this.audioPlayer.innerAudioContext.stop();
          // 如果点击的消息正在播放，就认为是停止播放操作
          if (playingMessage.messageId === audioMessage.messageId) {
            return;
          }
        }
        this.audioPlayer.playingMessage = audioMessage;
        this.audioPlayer.innerAudioContext.src = url;
        this.audioPlayer.innerAudioContext.play();
      },
      previewImage(item) {
        // 预览图片
        let imagesUrl = [item.payload.url];
        uni.previewImage({
          urls: imagesUrl // 需要预览的图片http链接列表
        });
      },
      selectEmoji(emojiKey) {
        // 选择表情
        this.text += emojiKey;
      },
      messageInputFocusin() {
        this.otherTypesMessagePanelVisible = false;
        this.emoji.visible = false
      },
      switchEmojiKeyboard() {
        if (!this.emoji.visible) {
          this.emoji.visible = true;
          this.otherTypesMessagePanelVisible = false;
          // 关闭手机键盘
          uni.hideKeyboard().then(console.log).catch(console.log);
        } else {
          this.emoji.visible = false;
          this.otherTypesMessagePanelVisible = false;
        }
      },
      showOtherTypesMessagePanel() {
        this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
        this.emoji.visible = false;
        // 关闭手机键盘
        uni.hideKeyboard().then(console.log).catch(console.log);
      },
    },
  }
</script>

<style scoped lang="scss">
  .box {
    padding: 36rpx 52rpx;
    box-sizing: border-box;
    text-align: center;

    .footer {
      display: flex;

      .footer-fl {
        width: 210rpx;
        height: 72rpx;
        border-radius: 74rpx;
        border: 2rpx solid #CCCCCC;
        font-family: PingFang SC, PingFang SC;
        font-weight: bold;
        font-size: 28rpx;
        color: #333333;
        text-align: center;
        line-height: 72rpx;
        margin-right: 30rpx;
      }

      .footer-fr {
        width: 210rpx;
        height: 72rpx;
        background: #4AA5EA;
        border-radius: 74rpx;
        font-family: PingFang SC, PingFang SC;
        font-weight: bold;
        font-size: 28rpx;
        color: #FFFFFF;
        text-align: center;
        line-height: 72rpx;
      }
    }

    .box-title {
      font-family: PingFang SC, PingFang SC;
      font-weight: bold;
      font-size: 32rpx;
      color: #000000;
      margin-bottom: 20rpx;
    }

    .dialog-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;

      .label {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #AAAAAA;
      }

      .dialog-ipt {
        width: 350rpx;
        height: 76rpx;
        background: #F7F8FA;
        border-radius: 20rpx 20rpx 20rpx 20rpx;
        padding: 0 10rpx;
      }

      .styles {
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 28rpx;
        color: #AAAAAA;
      }
    }
  }


  .chat {
    height: 100%;
    background-color: #F1F1F1;
  }

  .scroll-view {
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
    background-color: #F1F1F1;
    padding: 0 20rpx 210rpx 20rpx;
  }

  .history-loaded {
    font-size: 24rpx;
    height: 60rpx;
    line-height: 60rpx;
    color: #666666;
    width: 100%;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
  }

  .history-loaded image {
    height: 60rpx;
    line-height: 60rpx;
    margin: 15rpx 0;
    font-size: 24rpx;
    color: gray !important;
    text-decoration: none !important;
  }

  .load {
    font-size: 24rpx;
    height: 60rpx;
    line-height: 60rpx;
    margin: 15rpx 0;
    width: 100%;
    text-align: center;
    color: #d02129;
  }

  .time-lag {
    font-size: 20rpx;
    text-align: center;
  }

  .accept-message {
    width: 100%;
    display: flex;
    justify-content: center;
    font-size: 28rpx;
    padding: 20rpx 0;
    color: #A9A9A9;
  }

  .message-item {
    display: flex;
  }

  .message-item-content {
    flex: 1;
    margin-top: 15rpx;
    margin-bottom: 15rpx;
    overflow: hidden;
    display: flex;
  }

  .message-item-content.self {
    overflow: hidden;
    display: flex;
    justify-content: flex-start;
    flex-direction: row-reverse;
  }

  .message-item-content .avatar {
    width: 80rpx;
    height: 80rpx;
  }

  .message-item-content .avatar image {
    width: 80rpx;
    height: 80rpx;
  }

  .self {
    overflow: hidden;
    display: flex;
    justify-content: flex-start;
    flex-direction: row-reverse;
  }

  .other-icon {
    margin: 0 20rpx;
  }

  .self-icon {
    margin: 0 20rpx;
  }

  .content {
    font-size: 34rpx;
    line-height: 44rpx;
    max-width: 520rpx;
    margin: 0 20rpx;
  }

  .content .message-payload {
    display: flex;
    align-items: center;
  }

  .pending {
    width: 30rpx;
    height: 30rpx;
    padding: 10rpx;
  }

  .send-fail {
    width: 30rpx;
    height: 30rpx;
    margin-right: 10rpx;
  }

  .text-content {
    padding: 16rpx;
    border-radius: 12rpx;
    color: #000000;
    background: #ffffff;
    word-break: break-all;
    text-align: left;
    display: block;
  }

  .image-content {
    border-radius: 12rpx;
    width: 300rpx;
  }

  .image-content image {
    width: 100%;
    height: 100%;
  }

  .audio-content .audio-facade {
    display: flex;
    align-items: center;
    min-width: 80rpx;
    max-width: 300rpx;
    /* height: 60rpx; */
    padding: 6rpx 10rpx;
    border-radius: 14rpx;
    line-height: 72rpx;
    background: #ffffff;
    font-size: 24rpx;
    color: #000000;
  }

  .audio-content .audio-facade.self-sent {
    background: #FFFFFF;
    color: #ffffff;
    flex-direction: row-reverse;
  }

  .audio-content .audio-facade-bg {
    width: 40rpx;
    height: 35rpx;
  }

  .audio-content .record-second {
    padding-left: 10rpx;
    padding-right: 10rpx;
  }

  .video-snapshot {
    position: relative;
    max-height: 240rpx;
    max-width: 300rpx;
    overflow: hidden;
  }

  .thumbnail-image {
    max-height: 240rpx;
    max-width: 300rpx;
    background-color: #000000;
  }

  .play-icon {
    position: absolute;
    width: 80rpx;
    height: 80rpx;
    border-radius: 20rpx;
    top: 50%;
    left: 50%;
    margin-left: -40rpx;
    margin-top: -40rpx;
    z-index: 1000;
    opacity: 1;
  }

  .file-content {
    width: 480rpx;
    height: 120rpx;
    font-size: 28rpx;
    background: white;
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 20rpx;
    border-radius: 10rpx;
  }

  .file-info {
    width: 410rpx;
  }

  .file-name {
    width: 400rpx;
    line-height: 18px;
    text-overflow: ellipsis;
    overflow: hidden;
    word-break: break-all;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .file-size {
    color: #666666;
  }

  .file-img {
    width: 50rpx;
    height: 50rpx;
  }

  .custom-message {
    border-radius: 20rpx;
    background: #EFEFEF;
    padding: 16rpx;
    display: flex;
    flex-direction: column;
  }

  .order-content {
    border-radius: 20rpx;
    background: #FFFFFF;
    padding: 16rpx;
    display: flex;
    flex-direction: column;
  }

  .order-id {
    color: #333333;
  }

  .order-body {
    padding: 10rpx;
  }

  .order-name {
    font-weight: normal;
  }

  .order-info {
    display: flex;
    justify-content: space-between;
    padding: 10rpx;
  }

  .order-price {
    font-weight: normal;
  }

  .accept-session {
    width: 100%;
    height: 200rpx;
    position: fixed;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    bottom: 0;
    left: 0;
    z-index: 1000;
    background-color: #F1F1F1;
    border-top: 2rpx solid #E1E1E1;
  }

  .accept-info {
    font-size: 32rpx;
    margin-top: 20rpx;
    margin-left: 20rpx;
    line-height: 50rpx;
  }

  .accepted-info {
    width: 100%;
    font-size: 32rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #d02129;
  }

  .accept-btn {
    width: 130rpx;
    height: 60rpx;
    margin-top: 20rpx;
    margin-right: 20rpx;
    font-size: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #E8E8E8;
    color: #d02129;
    border-radius: 10rpx;
    cursor: pointer;
  }

  .action-box {
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 1000;
    background-color: #F1F1F1;
  }

  .session-action {
    display: flex;
    font-size: 28rpx;
    color: #57678E;
    padding-top: 20rpx;
    background-color: #F9F9F9;
    border-top: 2rpx solid #E0E0E0;
  }

  .session-action-item {
    width: 140rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    border-radius: 30rpx;
    background-color: #FFFFFF;
    margin-left: 20rpx;
  }

  .action-top {
    display: flex;
    align-items: center;
    width: 100%;
    height: 130rpx;
    padding: 20rpx;
    box-sizing: border-box;
    background-color: #F9F9F9;
  }

  .action-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .transfer-mask {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.5);
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 999;
  }

  .transfer-list {
    width: 100%;
    min-height: 280rpx;
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 1000;
    background-color: #FAFAFA;
    text-align: justify;
    font-size: 30rpx;
    border-radius: 20rpx;
  }

  .hide-transfer {
    display: flex;
    justify-content: flex-end;
    font-size: 28rpx;
  }

  .order-list {
    position: fixed;
    top: 0;
    bottom: 0;
    z-index: 1000;
    width: 100vw;
    height: 100vh;
    background: rgba(0, 0, 0, 0.5);
  }

  .orders-content {
    position: absolute;
    width: 100%;
    bottom: 0;
    background: #F1F1F1;
    z-index: 200;
  }

  .title {
    font-weight: 600;
    font-size: 30rpx;
    color: #000000;
    margin-left: 20rpx;
    margin-right: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    padding: 30rpx 0;
  }

  .close {
    position: absolute;
    left: 20rpx;
    font-size: 50rpx;
  }

  .transfer-body {
    display: flex;
    padding: 20rpx 0;
    border-bottom: 2rpx solid #F5F5F5;
  }

  .agent-img {
    margin-left: 40rpx;
    width: 80rpx;
    height: 80rpx;
  }

  .agent-name {
    font-size: 32rpx;
    line-height: 80rpx;
    margin-left: 20rpx;
  }

  .order-item {
    padding: 20rpx;
    background: #FFFFFF;
    margin: 20rpx;
    border-radius: 20rpx;
  }

  .order-id {
    font-size: 24rpx;
    color: #666666;
    margin-bottom: 10rpx;
  }

  .order-body {
    display: flex;
    font-size: 28rpx;
  }

  .order-img {
    width: 120rpx;
    height: 120rpx;
    border-radius: 10rpx;
  }

  .order-name {
    margin-left: 20rpx;
    width: 270rpx;
  }

  .order-right {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .order-price {
    font-weight: bold;
  }

  .order-count {
    font-size: 24rpx;
    color: #666666;
  }

  .microphone-icon {
    width: 45rpx;
    height: 50rpx;
    padding: 0 10rpx;
  }

  .keyboard-icon {
    width: 50rpx;
    height: 50rpx;
    padding: 0 10rpx;
  }

  .msg-input-box {
    flex: 1;
    height: 80rpx;
    padding-left: 20rpx;
    border-radius: 12rpx;
    box-sizing: border-box;
    line-height: 80rpx;
    font-size: 28rpx;
    background-color: #FFFFFF;
  }

  .more-icon {
    width: 58rpx;
    height: 58rpx;
    padding-left: 15rpx;
  }


  .send-btn-box {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 110rpx;
    height: 60rpx;
    border-radius: 10rpx;
    background: #D02129;
    margin-left: 15rpx;
  }

  .send-btn-box .btn {
    color: #FFFFFF;
    font-size: 28rpx;
  }

  .action-bottom {
    display: flex;
    flex-wrap: wrap;
    height: 350rpx;
    box-sizing: border-box;
    padding: 0 20rpx;
    background-color: #F9F9F9;
  }

  .action-popup {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }

  .action-popup .layer {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(51, 51, 51, 0.5);
    z-index: 999;
  }

  .action-popup .action-box {
    width: 350rpx;
    background: #434343;
    position: relative;
    z-index: 1000;
    border-radius: 20rpx;
    overflow: hidden;
  }

  .action-popup .action-item {
    text-align: center;
    height: 100rpx;
    line-height: 100rpx;
    font-size: 34rpx;
    color: #ffffff;
    border-bottom: 1px solid #EFEFEF;
  }

  .action-popup .action-item:last-child {
    border: none;
  }

  .messageSelector-box {
    display: flex;
    justify-content: center;
    align-items: center;
    backdrop-filter: blur(0.27rpx);
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    border-radius: 12rpx;
    background: #EFEFEF;
    height: 80rpx;
    padding: 20rpx 0;
    font-size: 32rpx;
  }

  .messageSelector-box .messageSelector-btn {
    width: 80rpx;
    height: 80rpx;
  }

  .image {
    height: 100rpx;
    width: 100rpx;
  }

  .more-item {
    display: flex;
    align-items: center;
    flex-direction: column;
    padding: 0 30rpx;
  }

  .operation-icon {
    width: 70rpx;
    height: 70rpx;
    padding: 25rpx;
    border-radius: 20rpx;
    background: #FFFFFF;
  }

  .operation-title {
    font-size: 24rpx;
    line-height: 50rpx;
    color: #82868E;
  }

  .more {
    width: 62rpx;
    height: 62rpx;
    margin-right: 10rpx;
    display: flex;
  }

  .action-box .action-top .record-input {
    flex: 1;
    width: 480rpx;
    height: 80rpx;
    line-height: 80rpx;
    padding-left: 20rpx;
    margin: 20rpx;
    margin-left: 0;
    border: none;
    outline: none;
    box-sizing: border-box;
    border-radius: 6px;
    background: #cccccc;
    color: #FFFFFF;
    font-size: 34rpx;
    text-align: center;
  }

  .record-loading {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 300rpx;
    height: 300rpx;
    margin: -150rpx -150rpx;
    background: #262628;
    background: url("~@/static/images/recording-loading.gif") no-repeat center;
    background-size: 100%;
    border-radius: 40rpx;
  }
</style>